package cn.jiadakeji.parent.controller;

import cn.jiadakeji.parent.common.constant.Constants;
import cn.jiadakeji.parent.common.core.domain.AjaxResult;
import cn.jiadakeji.parent.common.domian.WxPayment;
import cn.jiadakeji.parent.common.util.*;
import cn.jiadakeji.parent.domain.WxpayOrder;
import cn.jiadakeji.parent.mapper.WxpayOrderMapper;
import cn.jiadakeji.parent.service.TermCourseStudentService;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;

import static cn.jiadakeji.parent.common.constant.WechatConstants.*;

@Api(value = "微信支付", tags = "微信支付")
@RestController
@RequestMapping("/weiXinPay")
public class WeiXinPayController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WxpayOrderMapper orderMapper;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private TermCourseStudentService courseStudentService;

    @Transactional
    @ApiOperation("统一下单")
    @GetMapping("/wx/unifiedOrder")
    public AjaxResult createOrder(
            @ApiParam("预选课程ID")
            @RequestParam(value = "coursePreId", required = false) String coursePreId
    ) throws WxPayException, ServletException {
        // TODO:查找当前学生信息
        //TermCourseStudent student = courseStudentService.getStudent(coursePreId);
        //if (student == null) {
        //    throw new ServletException("当前订单错误");
        //}
        // 1,JSAPI下单    设置基本信息
        //String.format("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi?appid=%s&",
        //        );
        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = new WxPayUnifiedOrderRequest();
        wxPayUnifiedOrderRequest.setBody("测试");
        wxPayUnifiedOrderRequest.setOutTradeNo(IdUtils.fastSimpleUUID(16));
        wxPayUnifiedOrderRequest.setSpbillCreateIp("127.0.0.1");
        wxPayUnifiedOrderRequest.setTradeType("JSAPI");
        wxPayUnifiedOrderRequest.setTotalFee(100);
        wxPayUnifiedOrderRequest.setOpenid("oybkF5MBVTHMbIfLT2KI5KcnPE2g");
        //wxPayUnifiedOrderRequest.setOpenid(SecurityUtils.getLoginUser().getOpenId());
        //wxPayUnifiedOrderRequest.setNotifyUrl(WECHAT_NOTIFY_URL);
        wxPayUnifiedOrderRequest.setNotifyUrl("callBack");
        WxPayUnifiedOrderResult wxPayOrderQueryResult = wxPayService.unifiedOrder(wxPayUnifiedOrderRequest);

        // 2,订单信息存入数据库
        WxpayOrder wxpayOrder = new WxpayOrder();
        wxpayOrder.setTermCourseStudentId("lisi");
        //wxpayOrder.setCode();
        wxpayOrder.setStatus(Constants.TRADE_UNKNOWN);
        wxpayOrder.setTotalPrice(Long.valueOf(wxPayUnifiedOrderRequest.getTotalFee()));
        //wxpayOrder.setOrderType(wxPayUnifiedOrderRequest.getTradeType());
        wxpayOrder.setCreateBy("张三");
        wxpayOrder.setCustomerId("zhangsan");
        wxpayOrder.setAppId(wxPayUnifiedOrderRequest.getAppid());
        wxpayOrder.setMchId(wxPayUnifiedOrderRequest.getMchId());
        wxpayOrder.setBody(wxPayUnifiedOrderRequest.getBody());
        wxpayOrder.setOutTradeNo(wxPayUnifiedOrderRequest.getOutTradeNo());
        orderMapper.insert(wxpayOrder);

        // 3,生成小程序调起支付所需的数据
        WxPayment wxPayment = new WxPayment();
        wxPayment.setAppId(wxPayUnifiedOrderRequest.getAppid());
        wxPayment.setNonceStr(IdUtils.fastSimpleUUID(32));
        wxPayment.setSignType("MD5");
        //wxPayment.setPaySign();
        // 统一下单后结果中获取
        wxPayment.set_package("prepay_id=" + wxPayOrderQueryResult.getPrepayId());
        wxPayment.setTimeStamp(DateUtils.getNowDate().toString());
        wxPayment.sign(WECHAT_KEY);
        return AjaxResult.success(wxPayOrderQueryResult);
    }

    @ApiOperation("查询订单")
    @GetMapping("/queryOrder")
    public String queryOrder(
            @ApiParam("订单号")
            @RequestParam("outTradeNo") String outTradeNo
    ) {
        WxPayOrderQueryResult wxPayOrderQueryResult = null;
        try {
            wxPayOrderQueryResult = wxPayService.queryOrder(null, outTradeNo);
            if ("NOTPAY".equals(wxPayOrderQueryResult.getTradeState())) {
                return Constants.TRADE_UNKNOWN;
            }
            return Constants.TRADE_SUCCESS;
        } catch (WxPayException e) {
            e.printStackTrace();
        }
        return Constants.TRADE_FAIL;
    }

}
